package com.ktg.mes.md.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.core.page.TableDataInfo;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.utils.poi.ExcelUtil;
import com.ktg.mes.md.domain.ItemType;
import com.ktg.mes.md.domain.MdStatistics;
import com.ktg.mes.md.service.IMdStatisticsService;
import com.ktg.mes.unit.sql.domain.SQLCType;
import com.ktg.mes.unit.sql.domain.SQLDBConfig;
import com.ktg.mes.unit.sql.domain.SQLSortModel;
import com.ktg.mes.unit.sql.service.SQLToolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 统计分类Controller
 *
 * @author ruoyi
 * @date 2022-04-27
 */
@RestController
@RequestMapping("/mes/md/statistical")
public class MdStatisticalController extends BaseController
{
    @Autowired
    private IMdStatisticsService mdStatisticsService;

    @Autowired
    private SQLToolService sqlToolService;

    /**
     * 查询统计分类列表
     */
    @PreAuthorize("@ss.hasPermi('mes:md:statistical:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdStatistics mdStatistics)
    {
        startPage();
        List<MdStatistics> list = mdStatisticsService.selectMdStatisticsList(mdStatistics);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('mes:md:statistical:list')")
    @GetMapping("/list/exclude/{statisticsId}")
    public AjaxResult excludeChild(@PathVariable(value = "statisticsId",required = false)Long statisticsId){
        QueryWrapper<MdStatistics> queryWrapper = new QueryWrapper<>();
//        if (statisticsId != null){
//            queryWrapper.eq("parent_type_id",statisticsId);
//        }
        queryWrapper.orderByAsc("order_num  :: INT ");
        List<MdStatistics> list = mdStatisticsService.list(queryWrapper);
        return AjaxResult.success(list);
    }


    /**
     * 获取树形结构数据
     * @param itemType
     * @return
     */
    @GetMapping("/treeselect")
    public AjaxResult treeSelect(ItemType itemType){
        QueryWrapper<MdStatistics> queryWrapper = new QueryWrapper<>();
//        if (statisticsId != null){
//            queryWrapper.eq("parent_type_id",statisticsId);
//        }
        queryWrapper.orderByAsc("order_num  :: INT ");
        List<MdStatistics> list = mdStatisticsService.list(queryWrapper);
        return AjaxResult.success(mdStatisticsService.buildTreeSelect(list));
    }
    @PreAuthorize("@ss.hasPermi('mes:md:statistical:list')")
    @GetMapping("/listprimary")
    public AjaxResult listPrimary(){
        MdStatistics mdStatistics = new MdStatistics();
        List<MdStatistics> list = mdStatisticsService.selectMdStatisticsList(mdStatistics);
        return AjaxResult.success(list);
    }

    @GetMapping("/selectall")
    public AjaxResult selectAll(){
        MdStatistics mdStatistics = new MdStatistics();
        mdStatistics.setEnableFlag("Y");
        List<MdStatistics> list = mdStatisticsService.selectMdStatisticsList(mdStatistics);
        return AjaxResult.success(list);
    }

    /**
     * 导出统计分类列表
     */
    @PreAuthorize("@ss.hasPermi('mes:md:statistical:export')")
    @Log(title = "统计分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdStatistics mdStatistics)
    {
        List<MdStatistics> list = mdStatisticsService.selectMdStatisticsList(mdStatistics);
        ExcelUtil<MdStatistics> util = new ExcelUtil<MdStatistics>(MdStatistics.class);
        util.exportExcel(response, list, "统计分类数据");
    }

    /**
     * 获取统计分类详细信息
     */
    @PreAuthorize("@ss.hasPermi('mes:md:statistical:query')")
    @GetMapping(value = "/{measureId}")
    public AjaxResult getInfo(@PathVariable("measureId") Long measureId)
    {
        return AjaxResult.success(mdStatisticsService.selectMdStatisticsByMeasureId(measureId));
    }

    /**
     * 新增统计分类
     */
    @PreAuthorize("@ss.hasPermi('mes:md:statistical:add')")
    @Log(title = "统计分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MdStatistics mdStatistics)
    {

        QueryWrapper<MdStatistics> mdStatisticsQueryWrapper = new QueryWrapper<>();
        mdStatisticsQueryWrapper.eq("statistics_name",mdStatistics.getStatisticsName());
        Long count = mdStatisticsService.count(mdStatisticsQueryWrapper);
        if(count > 0){
            return AjaxResult.error("统计分类名称已存在");
        }
        mdStatistics.setUpdateTime(new Date());
        mdStatisticsService.insertMdStatistics(mdStatistics);

        //跟新排序
        SQLSortModel sqlSortModel = new SQLSortModel(SQLDBConfig.master,"md_statistics_type","statistics_id","order_num");
        if (mdStatistics.getParentTypeId() == null){
            sqlSortModel.addWhere("parent_type_id is null or parent_type_id = 0");
        }else {
            sqlSortModel.addWhere("parent_type_id",mdStatistics.getParentTypeId());
        }
        sqlToolService.updateSortModel(sqlSortModel);

        return AjaxResult.success(mdStatistics);
    }

    /**
     * 修改统计分类
     */
    @PreAuthorize("@ss.hasPermi('mes:md:statistical:edit')")
    @Log(title = "统计分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdStatistics mdStatistics)
    {

        MdStatistics old =  mdStatisticsService.getById(mdStatistics.getStatisticsId());
        int a = mdStatisticsService.updateMdStatistics(mdStatistics);

        if (old != null && old.getOrderNum() != mdStatistics.getOrderNum()){
            SQLSortModel sqlSortModel = new SQLSortModel(SQLDBConfig.master,"md_statistics_type","statistics_id","order_num");
            if (mdStatistics.getParentTypeId() == null){
                sqlSortModel.addWhere("parent_type_id is null or parent_type_id = 0");
            }else {
                sqlSortModel.addWhere("parent_type_id",mdStatistics.getParentTypeId());
            }
            sqlToolService.updateSortModel(sqlSortModel);
        }
//        SQLTool sqlTool = new SQLTool(SQLCType.SQLMain,"md_statistics_type");
//        sqlTool.addColumns("*");
//        List<Map> mapList = sqlToolService.selectSqlModel(sqlTool);
//        Integer count = mapList.size();

        return toAjax(a);
    }

    /**
     * 删除统计分类
     */
    @PreAuthorize("@ss.hasPermi('mes:md:statistical:remove')")
    @Log(title = "统计分类", businessType = BusinessType.DELETE)
	@DeleteMapping("/{measureIds}")
    public AjaxResult remove(@PathVariable Long[] measureIds)
    {
        return toAjax(mdStatisticsService.deleteMdStatisticsByMeasureIds(measureIds));
    }
}
